<template>
  <div class="schedule-wrapper">
    <div class="tip">*双击时间格即可预约实验室</div>
    <div class="calendar-wrapper">
      <div class="calendar-header">
        <div class="calendar-header-fixed">
          <div class="control-prev" @click="handleChangePrev"></div>
          <div class="control-text" @click="handleChangeCurrent">本周</div>
          <div class="control-next" @click="handleChangeNext"></div>
        </div>
        <div
          class="calendar-header-col"
          v-for="(item, index) in headers"
          :key="index"
          :class="{ 'has-event': dateHasEvent(item.fullDate) }"
        >
          <div class="date">{{ item.date }}</div>
          <div class="week">周{{ item.dayOfWeek }}</div>
        </div>
      </div>
      <div class="calendar-body">
        <div
          class="calendar-body-row"
          v-for="(item, index) in timeSlots"
          :key="index"
          :data-index="index"
        >
          <div class="calendar-body-fixed">
            {{ item }}
          </div>
          <div
            class="calendar-body-col"
            v-for="(card, key) in headers"
            :class="{ 'has-event': dateHasEvent(card.fullDate) }"
            :key="key"
          >
            <div class="event" @dblclick="handleAdd(card, item)"></div>
          </div>
        </div>
        <div class="calendar-card-box">
          <div
            class="calendar-card"
            v-for="(item, index) in listData"
            :key="index"
            :style="getCardStyle(item)"
            @click="handleCardClick(item)"
          >
            <div class="card-title">{{ item.title }}</div>
            <div class="card-content">
              {{ item.startTime }}~{{ item.endTime }}
            </div>
            <div class="card-content">{{ item.user }}</div>
          </div>
        </div>
      </div>
    </div>
    <!--新增/编辑-->
    <a-modal
      v-model:open="optionVisible"
      title="实验室预约"
      ok-text="确定预约"
      cancel-text="取消"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :maskClosable="false"
    >
      <a-form :model="formData" layout="vertical" ref="formRef">
        <a-form-item label="日期" name="appointment_date">
          <a-date-picker
            v-model:value="formData.appointment_date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="时间段" name="dateRange">
          <a-time-range-picker
            v-model:value="formData.dateRange"
            value-format="HH:mm"
            format="HH:mm"
          />
        </a-form-item>
        <a-form-item label="实验室" name="laboratory_id">
          <a-select
            v-model:value="formData.laboratory_id"
            placeholder="请选择实验室"
          >
            <a-select-option
              :value="item.value"
              v-for="(item, index) in laboratoryList"
              :key="index"
              >{{ item.label }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="实验名称" name="experiment_name">
          <a-input
            v-model:value="formData.experiment_name"
            placeholder="请输入实验名称"
          ></a-input>
        </a-form-item>
        <a-form-item label="器材/耗材" name="user_remark">
          <a-input
            v-model:value="formData.user_remark"
            placeholder="请输入器材/耗材"
          ></a-input>
        </a-form-item>

        <!-- <a-form-item label="器材" name="Equipment">
          <a-select
            v-model:value="formData.Equipment"
            placeholder="请选择器材"
            :max-tag-count="5"
            mode="multiple"
          >
            <a-select-option value="实验室1">实验室1</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="耗材" name="consumables">
          <a-select
            v-model:value="formData.consumables"
            placeholder="请选择耗材"
            mode="multiple"
            :max-tag-count="5"
          >
            <a-select-option value="实验室1">实验室1</a-select-option>
          </a-select>
        </a-form-item> -->
      </a-form>
    </a-modal>
    <a-modal
      v-model:visible="detailVisible"
      title="预约信息"
      ok-text="取消预约"
      cancel-text="关闭"
      @ok="handleCancelReservation"
      @cancel="() => (detailVisible.value = false)"
      :maskClosable="false"
      :destroyOnClose="true"
    >
      <div class="detail-content">
        <!-- 门禁密码 -->
        <div class="detail-item">
          <span class="label">门禁密码：</span>
          <span class="value">0000</span>
        </div>

        <!-- 日期 -->
        <div class="detail-item">
          <span class="label">日期：</span>
          <span class="value">{{ currentEvent?.appointment_date }}</span>
        </div>

        <!-- 起止时间 -->
        <div class="detail-item">
          <span class="label">起止时间：</span>
          <span class="value"
            >{{ currentEvent?.begin_time }}~{{ currentEvent?.end_time }}</span
          >
        </div>

        <!-- 实验名称 -->
        <div class="detail-item">
          <span class="label">实验名称：</span>
          <span class="value">{{ currentEvent?.experiment_name || "" }}</span>
        </div>

        <!-- 器材/耗材 -->
        <div class="detail-item">
          <span class="label">器材/耗材：</span>
          <span class="value">{{ currentEvent?.user_remark || "" }}</span>
        </div>
      </div>
    </a-modal>
  </div>
</template>
<script setup>
import { ref, onMounted, computed, nextTick } from "vue";
import dayjs from "dayjs"; // 用于日期格式化
import { message } from "ant-design-vue";
import api from "@/api";
dayjs.locale("zh-cn");
//当前日期
const currentDate = ref(new Date());
// 修改 headers 计算属性，增加 fullDate 字段（YYYY-MM-DD）
const headers = computed(() => {
  const result = [];
  const day = dayjs(currentDate.value);
  const monday = day.subtract(day.day() || 7, "day").add(1, "day"); // 定位到周一（关键修正）
  // 例如：currentDate 是周日（day.day()=0），则 monday = 周日 - 7天 +1天 = 周一
  // 例如：currentDate 是周三（day.day()=3），则 monday = 周三 -3天 +1天 = 周一

  for (let i = 0; i < 7; i++) {
    const currentDay = monday.add(i, "day");
    result.push({
      date: `${currentDay.month() + 1}-${String(currentDay.date()).padStart(
        2,
        "0"
      )}`,
      dayOfWeek: ["一", "二", "三", "四", "五", "六", "日"][i],
      fullDate: currentDay.format("YYYY-MM-DD"),
    });
  }
  return result;
});
// 切换到上一周
const handleChangePrev = () => {
  // currentDate 减去 7 天，触发 headers 重新计算为上一周
  currentDate.value = dayjs(currentDate.value).subtract(7, "day").toDate();
  // 切换后滚动到默认时间段（8:00~8:30，索引16）
  getListData();
  scrollToTimeSlot(17);
};
// 切换到本周（重置为当前日期所在周）
const handleChangeCurrent = () => {
  currentDate.value = new Date(); // 重置为今天
  getListData();
  // 切换后滚动到默认时间段
  scrollToTimeSlot(17);
};
// 切换到下一周
const handleChangeNext = () => {
  // currentDate 加上 7 天，触发 headers 重新计算为下一周
  currentDate.value = dayjs(currentDate.value).add(7, "day").toDate();
  getListData();
  // 切换后滚动到默认时间段
  scrollToTimeSlot(17);
};

// 时间段列表 0点到24点 每30分钟一个时间段
const timeSlots = ref([
  "0:00~0:30",
  "0:30~1:00",
  "1:00~1:30",
  "1:30~2:00",
  "2:00~2:30",
  "2:30~3:00",
  "3:00~3:30",
  "3:30~4:00",
  "4:00~4:30",
  "4:30~5:00",
  "5:00~5:30",
  "5:30~6:00",
  "6:00~6:30",
  "6:30~7:00",
  "7:00~7:30",
  "7:30~8:00",
  "8:00~8:30",
  "8:30~9:00",
  "9:00~9:30",
  "9:30~10:00",
  "10:00~10:30",
  "10:30~11:00",
  "11:00~11:30",
  "11:30~12:00",
  "12:00~12:30",
  "12:30~13:00",
  "13:00~13:30",
  "13:30~14:00",
  "14:00~14:30",
  "14:30~15:00",
  "15:00~15:30",
  "15:30~16:00",
  "16:00~16:30",
  "16:30~17:00",
  "17:00~17:30",
  "17:30~18:00",
  "18:00~18:30",
  "18:30~19:00",
  "19:00~19:30",
  "19:30~20:00",
  "20:00~20:30",
  "20:30~21:00",
  "21:00~21:30",
  "21:30~22:00",
  "22:00~22:30",
  "22:30~23:00",
  "23:00~23:30",
  "23:30~24:00",
]);
const listData = ref([
  {
    title: "开会",
    date: "2025-09-05",
    startTime: "10:00",
    endTime: "11:00",
    user: "张三",
  },
  {
    title: "开会1",
    date: "2025-09-01",
    startTime: "08:00",
    endTime: "08:20",
    user: "张三",
  },
  {
    title: "开会",
    date: "2025-09-05",
    startTime: "12:00",
    endTime: "13:00",
    user: "张三",
  },
]);
const optionVisible = ref();
const formData = ref({
  appointment_date: "",
  experiment_name: "",
  laboratory_id: null,
  dateRange: [],
  Equipment: [],
  consumables: [],
});
const laboratoryList = ref([]);
const getLaboratoryOptions = async () => {
  let res = await api.apiLaboratoryOptionsPost({});
  laboratoryList.value = res?.data;
};

const handleAdd = (card, timeSlot) => {
  const [startTimeStr, endTimeStr] = timeSlot.split("~"); // 分割时间段
  const fullDate = card.fullDate;
  // 格式化时间为 HH:mm（补全两位小时和分钟）
  const formatTime = (timeStr) => {
    const [hours, minutes] = timeStr.split(":").map(Number);
    // 补全小时和分钟为两位（如 8 → 08，5 → 05）
    return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(
      2,
      "0"
    )}`;
  };

  const start = formatTime(startTimeStr); // "8:00" → "08:00"
  const end = formatTime(endTimeStr); // "8:30" → "08:30"

  // 设置表单数据
  formData.value = {
    appointment_date: fullDate,
    dateRange: [start, end], // 绑定到 a-time-range-picker
    laboratory_id: null, // 重置其他字段
    experiment_name: "",
    Equipment: [],
    consumables: [],
  };
  optionVisible.value = true;
  console.log(2333, formData.value);
};
const handleSubmit = async () => {
  if (formData.value.laboratory_id === null) {
    message.error("请选择实验室");
    return;
  } else if (formData.value.experiment_name === "") {
    message.error("请输入实验名称");
    return;
  } else if (formData.value.appointment_date === "") {
    message.error("请选择日期");
    return;
  } else if (formData.value.dateRange.length !== 2) {
    message.error("请选择时间段");
    return;
  }

  let res = await api.apiAppointmentCreatePost({
    // ...formData.value,
    appointment_date: formData.value.appointment_date,
    begin_date: formData.value.dateRange[0],
    end_date: formData.value.dateRange[1],
    laboratory_id: formData.value.laboratory_id,
    experiment_name: formData.value.experiment_name,
    teacher_id: teacherOptions.value[0].teacher_id,
    user_remark: formData.value.user_remark,
  });
  if (res.statusCode === 200) {
    message.success("预约成功");
    optionVisible.value = false;
    getListData(); // 重新获取列表数据，确保界面更新
  }
};
const handleCancel = () => {
  formData.value = {
    appointment_date: "",
    experiment_name: "",
    laboratory_id: null,
    dateRange: [],
    Equipment: [],
    consumables: [],
  };
  optionVisible.value = false;
};
const detailVisible = ref(false);
const currentEvent = ref({}); // 当前点击的事件数据
// 点击卡片显示详情弹窗
const handleCardClick = async (event) => {
  let res = await api.apiAppointmentFetchModelPost({
    appointment_id: event.id,
  });

  if (res.statusCode === 200) {
    currentEvent.value = res?.data; // 存储当前事件数据
    currentEvent.value.appointment_date = currentEvent.value.appointment_date?.slice(0,11)

  }

  //后期看需不需要换成接口数据

  detailVisible.value = true; // 显示弹窗
};
// 取消预约（示例逻辑，实际需对接接口）
const handleCancelReservation = async () => {
  if (!currentEvent.value.id) return; // 非数据库事件（如本地测试数据）无需接口调用

  try {
    // 调用取消预约接口（根据实际接口调整）
    await api.apiAppointmentDeletePost({
      appointment_id: currentEvent.value.id,
    });

    detailVisible.value = false;
    getListData(); // 重新获取列表数据，确保界面更新
    message.success("取消预约成功！");
  } catch (error) {
    message.error("取消预约失败，请重试");
  }
};
const getListData = async () => {
  let params = {
    current: 1,
    pageSize: 9999,
    for_teacher: true,
    begin_dateRange: [headers.value[0].fullDate, headers.value[6].fullDate],
  };
  const res = await api.apiAppointmentPagedListPost({ args: params });
  console.log(111, res);
  listData.value = res?.data?.data.map((item) => {
    return {
      id: item.appointment_id,
      title: item.laboratory_name,
      date: item?.appointment_date ? item?.appointment_date?.split(" ")[0] : "",
      startTime: item.begin_time,
      endTime: item.end_time,
      user: item.teacher_name,
    };
  });
};
// 判断指定日期（header.fullDate）是否有事件
const dateHasEvent = (fullDate) => {
  return listData.value.some((event) => event.date === fullDate);
};
// 将时间字符串（如"10:00"）转换为当天的分钟数（0-1440）
const timeToMinutes = (timeStr) => {
  const [hours, minutes] = timeStr.split(":").map(Number);
  return hours * 60 + minutes;
};
// 获取事件在 timeSlots 中的起始索引（修正版）
const getTimeSlotIndex = (timeStr) => {
  const totalMinutes = timeToMinutes(timeStr);
  const index = totalMinutes / 30; // 每30分钟一个索引（必须是整数）
  if (!Number.isInteger(index)) {
    console.warn(`事件时间${timeStr}不是30分钟倍数，无法对齐`);
  }
  return index; // 例如：08:00 → 480分钟 → 480/30=16 → 对应索引16（"8:00~8:30"）
};
// 计算卡片样式（修正版）
const getCardStyle = (item) => {
  // 1. 打印调试信息，确认匹配情况
  const headersFullDates = headers.value.map((h) => h.fullDate);
  console.log("当前周日期:", headersFullDates);
  console.log(
    "事件日期:",
    item.date,
    "是否在当前周:",
    headersFullDates.includes(item.date)
  );

  // 2. 精确匹配列索引
  const colIndex = headers.value.findIndex(
    (header) => header.fullDate === item.date
  );
  if (colIndex === -1) return { display: "none" }; // 不在当前周则隐藏

  // 3. 水平位置：列索引 * 列宽（修正边框重叠）
  const colWidth = `calc(100% / 7)`;
  // 减去1px边框宽度（因为 .calendar-body-col 有1px边框，导致总宽度溢出）
  const left = `calc(${colIndex} * ${colWidth} + 1px - 1px)`;

  // 4. 垂直位置和高度（保持不变）
  const startIndex = getTimeSlotIndex(item.startTime);
  const endIndex = getTimeSlotIndex(item.endTime);
  return {
    left,
    top: `${startIndex * 78}px`,
    height: `${(endIndex - startIndex) * 78}px`,
    width: colWidth,
    boxSizing: "border-box",
  };
};

// 滚动到指定索引的时间段行
const scrollToTimeSlot = (targetIndex) => {
  // 等待 DOM 更新完成（避免获取不到元素）
  nextTick(() => {
    // 查找目标行（通过 data-index 属性）
    const targetRow = document.querySelector(
      `.calendar-body-row[data-index="${targetIndex}"]`
    );
    if (targetRow) {
      // 获取日历主体的滚动容器（.calendar-body）
      const scrollContainer = document.querySelector(".calendar-body");
      if (scrollContainer) {
        // 滚动到目标行的顶部位置（减去一定偏移量让内容居中）
        const scrollTop = targetRow.offsetTop - 100; // -100px 微调，避免贴顶
        scrollContainer.scrollTo({
          top: scrollTop,
          behavior: "smooth", // 平滑滚动（可选，移除则瞬间跳转）
        });
      }
    }
  });
};
//获取授课教师
const teacherOptions = ref([]);
const getApiUserMyTeacherIdsPost = async () => {
  //const res = await api.apiTeacherOptionsPost({ keyWords: '' });
  const res = await api.apiUserMyTeacherIdsPost();
  teacherOptions.value = res?.data;
};
// 初始化时设置默认日期（图片中的日期：2023年4月21日所在周）
onMounted(async () => {
  await getListData(); // 加载数据
  // 以 listData 中第一个事件的 date 作为基准周
  const firstEventDate = listData.value[0]?.date;
  if (firstEventDate) {
    const eventDay = dayjs(firstEventDate);
    // 设置 currentDate 为事件所在周的周一
    currentDate.value = eventDay.subtract(eventDay.day() - 1, "day").toDate();
  }
  scrollToTimeSlot(17); // 调用滚动方法
  await getLaboratoryOptions(); // 加载实验室选项
  await getApiUserMyTeacherIdsPost(); // 加载教师身份
});
</script>
<style lang="less" scoped>
.schedule-wrapper {
  width: 100%;
  height: 100%;
  background: #fff;
  padding: 16px;
  overflow: hidden;
  .tip{
    color:red;
    margin-bottom: 10px;
  }
  .calendar-wrapper {
    width: 100%;
    height: calc(100% - 32px);
    .calendar-header {
      display: flex;
      align-items: center;
      height: 78px;
      padding-right: 14px;
      .calendar-header-fixed {
        display: flex;
        width: 175px;
        height: 78px;
        align-items: center;
        padding: 0 16px;
        justify-content: space-between;
        background: linear-gradient(270deg, #ffffff 0%, #ecf0ff 100%);
        border: 1px solid #e6ebf1;
        .control-prev {
          width: 20px;
          height: 20px;
          cursor: pointer;
          background: url(@/assets/date-prev.png) no-repeat;
          background-size: 100%;
        }
        .control-text {
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
          font-size: 18px;
          color: #262626;
          line-height: 25px;
          font-style: normal;
          cursor: pointer;
        }
        .control-next {
          width: 20px;
          height: 20px;
          cursor: pointer;
          background: url(@/assets/date-next.png) no-repeat;
          background-size: 100%;
        }
      }
      .calendar-header-col {
        display: flex;
        flex: 1;
        height: 78px;
        justify-content: center;
        align-items: center;
        background: #fff9f2;
        border: 1px solid #e6ebf1;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 18px;
        color: #262626;
        line-height: 25px;
        &.has-event {
          background: #f2f2f2;
        }
      }
    }
    .calendar-body {
      width: 100%;
      height: calc(100% - 78px);
      overflow-y: auto;
      overflow-x: hidden;
      position: relative;
      .calendar-body-row {
        display: flex;
        align-items: center;
        height: 78px;
        .calendar-body-fixed {
          width: 175px;
          height: 78px;
          background: #ffffff;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 1px solid #e6ebf1;
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
          font-size: 18px;
          color: #262626;
          line-height: 25px;
        }
        .calendar-body-col {
          flex: 1;
          cursor: pointer;
          height: 78px;
          background: #fff9f2;
          border: 1px solid #e6ebf1;
          .event {
            width: 100%;
            height: 100%;
          }
          &.has-event {
            background: #fff;
          }
        }
      }
      .calendar-card-box {
        position: absolute;
        top: 0;
        width: calc(
          100% - 175px
        ); // 右侧内容区宽度（修正之前 width:100% 的错误）
        left: 175px;
        height: 100%;
        pointer-events: none; // 避免遮挡下方点击区域
        .calendar-card {
          overflow: hidden;
          position: absolute; // 绝对定位
          box-sizing: border-box; // 宽高包含内边距和边框
          border-top: 6px solid #426bff;
          background: #ecf0ff;
          padding: 16px 12px;
          pointer-events: auto; // 恢复卡片自身的交互能力
          cursor: pointer;
          .card-title {
            font-family: PingFangSC, PingFang SC;
            font-weight: 500;
            font-size: 16px;
            color: #426bff;
            line-height: 26px;
            text-align: left;
            font-style: normal;
          }
          .card-content {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 14px;
            color: #426bff;
            line-height: 24px;
            text-align: left;
            font-style: normal;
          }
        }
      }
    }
  }
}
/* 详情弹窗样式 */
.detail-content {
  padding-top: 20px;
  .detail-item {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    .label {
      width: 100px;
      color: #555;
      font-weight: 500;
    }
    .value {
      flex: 1;
      color: #333;
    }
    .badge {
      margin-left: 10px;
      padding: 2px 8px;
      background: #ff4d4f;
      color: white;
      border-radius: 12px;
      font-size: 12px;
    }
  }
}

/* 调整卡片鼠标样式（点击提示） */
.calendar-card {
  cursor: pointer;
  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 悬停阴影效果 */
  }
}
</style>
